//
//  WithdrawWXViewController.m
//  HTHappySale
//
//  Created by 创维海通 on 2017/9/26.
//  Copyright © 2017年 zxyywy. All rights reserved.
//

#import "WithdrawWXViewController.h"
#import "WithdrawSuccessViewController.h"
#import "BalanceViewController.h"

//Cell
#import "WithdrawWXCell.h"

//Request
#import "HTTPPromise+Me.h"

//Model
#import "MeHTModel.h"

//Tools
#import "UIViewController+KeyboardCorver.h"
#import "AppUtil.h"

@interface WithdrawWXViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    float_t moneyValue;
}
@property (strong, nonatomic) IBOutlet UITableView *WXTableView;
@property (strong, nonatomic) UIView *headerView;

@property (strong, nonatomic) MeWithdrawSuccessModel *model;

@end

@implementation WithdrawWXViewController
#pragma mark -init
#define WithdrawWXIdentifyCell  @"WithdrawWXCell"

#pragma mark -懒加载
- (UIView *)headerView
{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 160)];
        _headerView.backgroundColor = [UIColor whiteColor];
        
        UILabel *explanLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 110, 10, 90, 20)];
        explanLabel.text = @"提现说明";
        explanLabel.textAlignment = NSTextAlignmentRight;
        explanLabel.textColor = HTCFQuickRGBColor(159,159,159);
        explanLabel.userInteractionEnabled = YES;
        UITapGestureRecognizer *balanceAction = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(skipBalanceController)];
        [explanLabel addGestureRecognizer:balanceAction];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_headerView.frame) / 2 - 50, 30, 100, 100)];
        imageView.image = HTCFQuickImage(@"balance");
        
        UILabel *priceLabel = [[UILabel alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - 200) / 2, CGRectGetMaxY(imageView.frame) + 10, 200, 20)];
        NSString *moneyStr =[NSString stringWithFormat:@"余额￥%.2f元",moneyValue];
        NSInteger len = [moneyStr length];
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:moneyStr];
        
        //设置：在0-3个单位长度内的内容显示成红色
        [str addAttribute:NSForegroundColorAttributeName value:HTCFQuickRGBColor(159, 159, 159) range:NSMakeRange(0, 2)];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(2, len-3)];
        [str addAttribute:NSForegroundColorAttributeName value:HTCFQuickRGBColor(159, 159, 159) range:NSMakeRange(len-1, 1)];
        
        priceLabel.attributedText = str;
        
        [_headerView addSubview:explanLabel];
        [_headerView addSubview:imageView];
        [_headerView addSubview:priceLabel];
    }
    return _headerView;
}

- (instancetype)init:(float_t)withdrawPrice
{
    if (self = [super init]) {
        moneyValue = withdrawPrice;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //Xib
    UINib *contentNib = [UINib nibWithNibName:NSStringFromClass([WithdrawWXCell class])
                                       bundle:[NSBundle mainBundle]];
    [self.WXTableView registerNib:contentNib forCellReuseIdentifier:WithdrawWXIdentifyCell];
    
    [self initTableView];
    [self addNotification];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self addNavigationLeftView:@"" andType:0];
    [self addNavigationMiddleView:@"提现至微信"];
}

- (void)initTableView
{
    _WXTableView.tableFooterView = [[UIView alloc] init];
    _WXTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _WXTableView.tableHeaderView = self.headerView;
    _WXTableView.scrollEnabled = NO;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

#define cellIdentify @"cell"
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0)
    {
        WithdrawWXCell *withdrawWXCell = [tableView dequeueReusableCellWithIdentifier:WithdrawWXIdentifyCell];
        [withdrawWXCell configureCell:moneyValue];
        withdrawWXCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return withdrawWXCell;
    }else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
        
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
        }
        
        UIButton *ApplyOfBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        ApplyOfBtn.frame = CGRectMake(20, 10, SCREEN_WIDTH - 40, 30);
        [ApplyOfBtn setBackgroundColor:HTCFQuickRGBColor(51,190,0)];
        [ApplyOfBtn setTitle:@"申请提现" forState:UIControlStateNormal];
        [ApplyOfBtn addTarget:self action:@selector(submitRequest) forControlEvents:UIControlEventTouchUpInside];
        ApplyOfBtn.layer.masksToBounds = YES;
        ApplyOfBtn.layer.cornerRadius = 10;
        
        [cell addSubview:ApplyOfBtn];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0)
    {
        return 80;
    }
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0)
    {
        return 80;
    }
    return 50;
}

- (void)submitRequest{
    UITextField *textField = [_WXTableView viewWithTag:801];
    float_t tempPrice = [textField.text floatValue];
    if(tempPrice <= 0 && tempPrice < moneyValue)
    {
        [AppUtil showTipMessage:@"请输入金额"];
        return;
    }
    
    NSDictionary *purseListParam = @{@"amount":[NSString stringWithFormat:@"%.2f",tempPrice]};
    NSData *jsonData;
    
    if ([NSJSONSerialization isValidJSONObject:purseListParam])
    {
        NSError *error;
        jsonData = [NSJSONSerialization dataWithJSONObject:purseListParam options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"json data:%@",json);
    }
    
    __weak __typeof(self)weakSelf = self;
    [HTTPPromise requestWithdrawCashParams:jsonData Success:^(id responseObj) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSLog(@"%@",responseObj);
        
        int successRet =[responseObj[@"ret"] intValue];
        //(数据转模型）
        if (successRet == 0) {
            strongSelf->_model = [[MeWithdrawSuccessModel alloc] init];
            strongSelf->_model.amount = [responseObj[@"amount"] floatValue];
            strongSelf->_model.weekday = responseObj[@"weekday"];
            
            [strongSelf skipController];
        }else{
            [AppUtil showTipMessage:responseObj[@"desc"]];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error.userInfo);
    }];
}

- (void)skipController{
    WithdrawSuccessViewController *successVC = [[WithdrawSuccessViewController alloc] init:_model];
    [self.navigationController pushViewController:successVC animated:YES];
}

- (void)skipBalanceController
{
    BalanceViewController *balanceVC = [[BalanceViewController alloc] init];
    [self.navigationController pushViewController:balanceVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
